<template>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="bigForm"
             style="width: 600px;margin-left: 20em">
        <el-form-item label="项目图片" class="img">
            <div class="upload">
                <el-upload
                        class="uploadFile"
                        :action=domain/*提交表单*/
                        :http-request=reqServer/*请求服务器*/
                        :show-file-list="false"
                        :before-upload="checkFile">
                    <!-- wzy todo:imgUrl 存在-->
                    <img v-if="imgUrl" :src="imgUrl" alt="加载失败" class="uploadFile-Button">
                    <i v-else class="el-icon-plus addProjectIg"></i>
                </el-upload>
            </div>
        </el-form-item>

        <el-form-item label="项目名称" prop="name">
            <el-input placeholder="项目名称" v-model="ruleForm.name"></el-input>
        </el-form-item>

        <el-form-item label="项目描述" prop="desc">
            <el-input placeholder="项目描述" v-model="ruleForm.desc"></el-input>
        </el-form-item>


        <el-form-item label="项目环境" prop="selectEnv">
            <el-select
                    clearable
                    placeholder="项目运行API前缀，*必填"
                    v-model="ruleForm.searchValue"
                    @change="changeValue"
                    filterable
                    allow-create
                    default-first-option
                    @blur="searchBlur"
                    style="width: 500px"
            >
                <el-option v-for="item in options" :key="item.label" :label="item.value" :value="item.label">
                </el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="配置环境" prop="select">
            <el-select v-model="ruleForm.config" filterable
                       allow-create
                       :blur="searchBlur1"
                       default-first-option clearable placeholder="非必填" style="width: 500px">
                <el-option
                        v-for="item in options"
                        :key="item.label"
                        :label="item.value"
                        :value="item.label">
                </el-option>
            </el-select>
        </el-form-item>
        <!--        增加 取消-->
        <el-form-item>
            <el-button type="primary" @click="addProjectData('ruleForm')">创建</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
    //                           ↓ 防止ES检查报错
    var runningAddress = "";// eslint-disable-line no-unused-vars
    import {Message} from 'element-ui'
    import {addproject, uploadtoken} from "../../request/api.js";
    import base from "../../request/base";
    import axios from 'axios';
    import router from '../../router/index'

    export default {
        name: "addProject",
        data() {
            return {
                ruleForm: {
                    name: '',
                    desc: '',
                    searchValue: '',
                    config: '',
                    otherConfig: ''
                },
                options: [{
                    value: 'http://127.0.0.1:6868',
                    label: 'http://127.0.0.1:6868'
                }],
                imgUrl: '',
                token: '',
                domain: '', // 上传文件地址
                reqServerUrl: base.url, // 请求域名
                rules: { // 过滤规则
                    name: [
                        {
                            required: true,  // 必填项
                            message: "请输入项目名称",
                            trigger: 'blur' // 触发器:焦点移出后
                        },
                        {
                            min: 2,
                            max: 30,
                            message: "长度在2~30之间",
                            trigger: 'blur'
                        }
                    ],
                    desc: [{
                        required: true,
                        message: "请输入项目描述",
                        trigger: 'blur'
                    }, {
                        min: 2,
                        max: 30,
                        message: "长度在2~30之间",
                        trigger: 'blur'
                    }]
                }


            }
        },
        mounted() {
        },
        methods: {
            // 焦点移出后出发
            searchBlur(e) { // e.target 获取当前事件  与this不要弄混
                console.log("移除焦点后：" + e.target.value)
                this.ruleForm.searchValue = e.target.value;
                runningAddress = e.target.value;
            },
            searchBlur1(e) {
                console.log(e.target.value)
                this.ruleForm.otherConfig = e.target.value
            },
            // 值改变的时候
            changeValue(label) {
                let obj = {};
                if (label != ""){
                    obj = this.options.find((item) => {
                    return item.label === label; // 判断是否存在
                });
                console.log("obj.label", obj.label);
                runningAddress = obj.label;
                console.log("值改变runAddress", runningAddress);
                }
                else {
                    runningAddress = ""
                }

            },
            changeValue1(label) {
                let obj = {};
                if (label != ""){
                    obj = this.options.find((item) => {
                    return item.label === label; // 判断是否存在
                });
                console.log("obj.label", obj.label);
                runningAddress = obj.label;
                }
                else {
                    runningAddress = ""
                }

            },
            // 重置表单数据按钮
            resetForm(form) {
                this.$refs[form].resetFields();
            },
            addProjectData(form) {
                var infoDat = {
                    data: JSON.stringify({
                        name: this.ruleForm.name,
                        imageUrl: "https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=element&step_word=&hs=0&pn=0&spn=0&di=196240&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=1518217176%2C930388838&os=2201319281%2C722597566&simid=3489056428%2C302701433&adpicid=0&lpn=0&ln=1647&fr=&fmq=1597484913940_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fwww.thoughtco.com%2Fthmb%2FzfnQ1qqZvjq7Xt5dmzuWZkWL1F4%3D%2F768x0%2Ffilters%3Ano_upscale()%3Amax_bytes(150000)%3Astrip_icc()%2FElement_Logo_Med-56a8757f5f9b58b7d0f2ad98.gif&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bpi572ipv5_z%26e3Bv54AzdH3Ffhwpjk5w61-s525f-rtvf-w6vitej-98dn8c8&gsm=1&rpstart=0&rpnum=0&islist=&querylist=&force=undefined",
                        describe: this.ruleForm.desc,
                        formCfg: this.ruleForm.config,
                        configure_address: this.ruleForm.otherConfig,
                        runningAddress: this.ruleForm.searchValue
                    }),
                }
                console.log(infoDat)
                try {
                    if (runningAddress == null || runningAddress == "") {
                        console.log("项目API"+runningAddress)
                        Message.warning("确认项目API地址前缀，是否正常！");
                    } else {
                        this.$refs[form].validate((valid) => {// 表单验证
                            if (valid) {
                                addproject(infoDat).then(function (data) { // 提交表单数据 addproject
                                    var resData = data.data;
                                    if (resData["code"] == 200) {
                                        Message.info("新增成功");
                                        router.push('/index');

                                    }
                                    if (resData["code"] == 201) {
                                        Message.error(resData["msg"]);
                                    }
                                    if (resData["code"] == 401) {
                                        Message.error(resData["msg"]);
                                    }
                                });
                            } else {
                                Message.error("错误，请重试!");
                                return false;
                            }
                        });
                    }
                } finally {// 清空当前
                    this.imgUrl = '';
                    this.desc = '';
                    this.config = '';
                    this.otherConfig = '';
                    runningAddress = ''
                }
            },
            reqServer(file) { // 上传图片
                const config = {
                    headers: {'Content-Type': 'multipart/form-data'}
                }
                let filetype = '';
                if (file.file.type === 'image/png') {
                    // todo 扩展图片类型
                    filetype = 'png';
                } else {
                    filetype = 'jpg';
                }
                console.log("upload----type:", filetype)
                // todo 上传图片类型 待优化
                const keyName = "bilibili" + new Date().getTime() + Math.floor(Math.random() * 1000) + "." + filetype
                uploadtoken().then(res => {
                    const uploadImg = new FormData();
                    uploadImg.append('file', file.file);
                    uploadImg.append('token', res["uptoken"]);
                    uploadImg.append('key', keyName);
                    axios.post(this.domain, uploadImg, config).then(res => {
                        this.imgUrl = 'http://' + this.reqServerUrl + '/' + res.data.key
                        console.log(this.imgUrl)
                    });
                });
            },
            // 验证文件合法
            checkFile(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            }
        }
    }
</script>

<style lang="scss" scoped>

</style>